<template>
  <view class="consult-container">
    <!-- 顶部专家信息 -->
    <view class="expert-header">
      <view class="expert-info">
        <u-avatar :src="expert.avatar" size="40"></u-avatar>
        <view class="expert-details">
          <text class="expert-name">{{ expert.name }}</text>
          <view class="expert-status">
            <view v-if="expert.isOnline" class="online-indicator">
              <view class="online-dot"></view>
              <text class="status-text">在线</text>
            </view>
            <view v-else class="offline-indicator">
              <text class="status-text">离线</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="consult-info">
        <text class="service-type">{{ serviceTypeText }}</text>
        <text class="remaining-time" v-if="remainingTime > 0">
          剩余时间：{{ formatTime(remainingTime) }}
        </text>
      </view>
    </view>
    
    <!-- 聊天消息区域 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
    >
      <!-- 加载更多提示 -->
      <view v-if="loadingMore" class="loading-more">
        <u-loading-icon size="20"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 消息列表 -->
      <view 
        v-for="(message, index) in messageList" 
        :key="message.id"
        class="message-item"
        :class="{ 'message-self': message.fromUser }"
      >
        <!-- 时间分隔线 -->
        <view v-if="shouldShowTime(index)" class="time-divider">
          <text class="time-text">{{ formatMessageTime(message.createTime) }}</text>
        </view>
        
        <!-- 消息内容 -->
        <view class="message-content">
          <u-avatar 
            v-if="!message.fromUser" 
            :src="expert.avatar" 
            size="35"
            class="message-avatar"
          ></u-avatar>
          
          <view class="message-bubble" :class="{ 'bubble-self': message.fromUser }">
            <!-- 文本消息 -->
            <text v-if="message.type === 'text'" class="message-text">
              {{ message.content }}
            </text>
            
            <!-- 图片消息 -->
            <image 
              v-else-if="message.type === 'image'"
              :src="message.content"
              class="message-image"
              mode="aspectFit"
              @click="previewImage(message.content)"
            ></image>
            
            <!-- 语音消息 -->
            <view v-else-if="message.type === 'voice'" class="voice-message" @click="playVoice(message)">
              <u-icon 
                :name="message.playing ? 'pause' : 'play-circle'" 
                size="20" 
                color="white"
              ></u-icon>
              <text class="voice-duration">{{ message.duration }}"</text>
            </view>
            
            <!-- 系统消息 -->
            <text v-else-if="message.type === 'system'" class="system-message">
              {{ message.content }}
            </text>
          </view>
          
          <u-avatar 
            v-if="message.fromUser" 
            :src="userAvatar" 
            size="35"
            class="message-avatar"
          ></u-avatar>
        </view>
        
        <!-- 消息状态 -->
        <view v-if="message.fromUser" class="message-status">
          <text v-if="message.status === 'sending'" class="status-text">发送中</text>
          <text v-else-if="message.status === 'failed'" class="status-text error">发送失败</text>
          <text v-else-if="message.status === 'read'" class="status-text">已读</text>
        </view>
      </view>
      
      <!-- 专家正在输入提示 -->
      <view v-if="expertTyping" class="typing-indicator">
        <u-avatar :src="expert.avatar" size="35" class="message-avatar"></u-avatar>
        <view class="typing-bubble">
          <view class="typing-dots">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部输入区域 -->
    <view class="input-area">
      <!-- 语音/视频通话按钮 -->
      <view v-if="serviceType !== 'text'" class="call-buttons">
        <u-button 
          v-if="serviceType === 'voice' || serviceType === 'video'"
          class="call-btn voice-btn"
          :disabled="!expert.isOnline"
          @click="startVoiceCall"
        >
          <u-icon name="mic" size="18" color="white"></u-icon>
          <text class="btn-text">语音通话</text>
        </u-button>
        
        <u-button 
          v-if="serviceType === 'video'"
          class="call-btn video-btn"
          :disabled="!expert.isOnline"
          @click="startVideoCall"
        >
          <u-icon name="camera" size="18" color="white"></u-icon>
          <text class="btn-text">视频通话</text>
        </u-button>
      </view>
      
      <!-- 消息输入框 -->
      <view class="message-input-area">
        <view class="input-tools">
          <u-icon 
            name="plus-circle" 
            size="24" 
            color="#666" 
            @click="showMoreOptions"
          ></u-icon>
        </view>
        
        <input 
          v-model="inputText"
          class="message-input"
          placeholder="输入消息..."
          :disabled="!canSendMessage"
          @confirm="sendTextMessage"
          @input="onInputChange"
        />
        
        <view class="send-area">
          <u-button 
            v-if="inputText.trim()"
            type="primary"
            size="small"
            class="send-btn"
            :disabled="!canSendMessage"
            @click="sendTextMessage"
          >
            发送
          </u-button>
          
          <u-icon 
            v-else
            name="mic" 
            size="24" 
            color="#007aff"
            @click="startVoiceRecord"
          ></u-icon>
        </view>
      </view>
    </view>
    
    <!-- 更多选项弹窗 -->
    <u-popup 
      v-model="showOptionsPopup" 
      mode="bottom" 
      border-radius="20"
      :safe-area-inset-bottom="true"
    >
      <view class="options-popup">
        <view class="popup-header">
          <text class="popup-title">更多选项</text>
          <u-icon name="close" size="20" color="#999" @click="showOptionsPopup = false"></u-icon>
        </view>
        
        <view class="option-grid">
          <view class="option-item" @click="selectImage">
            <view class="option-icon">
              <u-icon name="image" size="24" color="#007aff"></u-icon>
            </view>
            <text class="option-text">相册</text>
          </view>
          
          <view class="option-item" @click="takePhoto">
            <view class="option-icon">
              <u-icon name="camera" size="24" color="#4caf50"></u-icon>
            </view>
            <text class="option-text">拍照</text>
          </view>
          
          <view class="option-item" @click="showConsultHistory">
            <view class="option-icon">
              <u-icon name="clock" size="24" color="#ff9500"></u-icon>
            </view>
            <text class="option-text">历史记录</text>
          </view>
          
          <view class="option-item" @click="evaluateExpert">
            <view class="option-icon">
              <u-icon name="star" size="24" color="#ffd700"></u-icon>
            </view>
            <text class="option-text">评价专家</text>
          </view>
        </view>
      </view>
    </u-popup>
    
    <!-- 语音录制弹窗 -->
    <u-popup 
      v-model="showVoiceRecord" 
      mode="center"
      width="600rpx"
      height="400rpx"
      border-radius="20"
    >
      <view class="voice-record-popup">
        <view class="record-header">
          <text class="record-title">语音录制</text>
        </view>
        
        <view class="record-content">
          <view class="record-animation">
            <view class="record-circle" :class="{ recording: isRecording }">
              <u-icon name="mic" size="40" color="white"></u-icon>
            </view>
          </view>
          
          <text class="record-time">{{ formatRecordTime(recordTime) }}</text>
          <text class="record-tip">
            {{ isRecording ? '正在录制，松开发送' : '按住录制语音' }}
          </text>
        </view>
        
        <view class="record-actions">
          <u-button 
            class="record-btn"
            :class="{ recording: isRecording }"
            @touchstart="startRecord"
            @touchend="stopRecord"
            @touchcancel="cancelRecord"
          >
            {{ isRecording ? '松开发送' : '按住录制' }}
          </u-button>
          
          <u-button 
            class="cancel-btn"
            @click="showVoiceRecord = false"
          >
            取消
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';

// 专家接口
interface Expert {
  id: string;
  name: string;
  avatar: string;
  isOnline: boolean;
}

// 消息接口
interface Message {
  id: string;
  type: 'text' | 'image' | 'voice' | 'system';
  content: string;
  fromUser: boolean;
  createTime: string;
  status?: 'sending' | 'sent' | 'read' | 'failed';
  duration?: number;
  playing?: boolean;
}

// 咨询订单接口
interface ConsultOrder {
  id: string;
  expertId: string;
  serviceType: string;
  status: string;
  startTime: string;
  endTime?: string;
  duration: number;
}

@Component
export default class ConsultPage extends Vue {
  // 数据属性
  orderId: string = '';
  expertId: string = '';
  serviceType: string = 'text';
  
  expert: Expert = {} as Expert;
  consultOrder: ConsultOrder = {} as ConsultOrder;
  messageList: Message[] = [];
  
  inputText: string = '';
  scrollTop: number = 0;
  
  expertTyping: boolean = false;
  loadingMore: boolean = false;
  
  showOptionsPopup: boolean = false;
  showVoiceRecord: boolean = false;
  
  isRecording: boolean = false;
  recordTime: number = 0;
  recordTimer: any = 0;
  
  remainingTime: number = 0;
  timeTimer: any = 0;
  countdownTimer: any = 0;
  
  userAvatar: string = '';
  
  // 计算属性
  get serviceTypeText(): string {
    const typeMap: Record<string, string> = {
      text: '图文咨询',
      voice: '语音咨询',
      video: '视频咨询'
    };
    return typeMap[this.serviceType] || '咨询服务';
  }
  
  get canSendMessage(): boolean {
    return this.consultOrder.status === 'active' && this.remainingTime > 0;
  }
  
  // 生命周期
  onLoad(options: any) {
    this.orderId = options.orderId || '';
    this.expertId = options.expertId || '';
    this.serviceType = options.serviceType || 'text';
    
    if (this.orderId) {
      this.loadConsultOrder();
    } else if (this.expertId) {
      this.loadExpertInfo();
    }
    
    this.loadMessages();
    this.initUserInfo();
    this.startTimeCounter();
  }
  
  onUnload() {
    this.clearTimers();
  }
  
  // 方法
  
  /**
   * 加载咨询订单信息
   */
  async loadConsultOrder() {
    try {
      const response = await get(`/consult/orders/${this.orderId}`);
      this.consultOrder = response.data.order;
      this.expertId = this.consultOrder.expertId;
      this.serviceType = this.consultOrder.serviceType;
      
      // 计算剩余时间
      if (this.consultOrder.status === 'active') {
        const startTime = new Date(this.consultOrder.startTime).getTime();
        const now = Date.now();
        const elapsed = Math.floor((now - startTime) / 1000);
        this.remainingTime = Math.max(0, this.consultOrder.duration * 60 - elapsed);
      }
      
      await this.loadExpertInfo();
    } catch (error) {
      console.error('加载订单信息失败:', error);
      
      // 使用模拟数据
      this.consultOrder = this.getMockOrder();
    }
  }
  
  /**
   * 加载专家信息
   */
  async loadExpertInfo() {
    try {
      const response = await get(`/experts/detail/${this.expertId}`);
      this.expert = response.data.expert;
    } catch (error) {
      console.error('加载专家信息失败:', error);
      
      // 使用模拟数据
      this.expert = this.getMockExpert();
    }
  }
  
  /**
   * 加载消息列表
   */
  async loadMessages(isLoadMore: boolean = false) {
    if (this.loadingMore && isLoadMore) return;
    
    if (isLoadMore) {
      this.loadingMore = true;
    }
    
    try {
      const response = await get('/consult/messages', {
        orderId: this.orderId,
        expertId: this.expertId,
        page: isLoadMore ? Math.floor(this.messageList.length / 20) + 1 : 1,
        pageSize: 20
      });
      
      const newMessages = response.data.messages || [];
      
      if (isLoadMore) {
        this.messageList = [...newMessages, ...this.messageList];
      } else {
        this.messageList = newMessages;
        this.scrollToBottom();
      }
      
    } catch (error) {
      console.error('加载消息失败:', error);
      
      // 使用模拟数据
      if (!isLoadMore) {
        this.messageList = this.getMockMessages();
        this.scrollToBottom();
      }
    } finally {
      if (isLoadMore) {
        this.loadingMore = false;
      }
    }
  }
  
  /**
   * 初始化用户信息
   */
  initUserInfo() {
    const userInfo = uni.getStorageSync('userInfo');
    this.userAvatar = userInfo?.avatar || 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=user%20avatar&image_size=square';
  }
  
  /**
   * 开始时间计数器
   */
  startTimeCounter() {
    this.countdownTimer = setInterval(() => {
      if (this.remainingTime > 0) {
        this.remainingTime--;
      } else {
        this.clearTimers();
        this.endConsultation();
      }
    }, 1000);
  }
  
  /**
   * 清除定时器
   */
  clearTimers() {
    if (this.timeTimer) {
      clearInterval(this.timeTimer);
      this.timeTimer = 0;
    }
    if (this.recordTimer) {
      clearInterval(this.recordTimer);
      this.recordTimer = 0;
    }
  }
  
  /**
   * 结束咨询
   */
  endConsultation() {
    uni.showModal({
      title: '咨询结束',
      content: '本次咨询已结束，感谢您的使用！',
      showCancel: false,
      success: () => {
        uni.navigateBack();
      }
    });
  }
  
  /**
   * 发送文本消息
   */
  async sendTextMessage() {
    if (!this.inputText.trim() || !this.canSendMessage) return;
    
    const message: Message = {
      id: Date.now().toString(),
      type: 'text',
      content: this.inputText.trim(),
      fromUser: true,
      createTime: new Date().toISOString(),
      status: 'sending'
    };
    
    this.messageList.push(message);
    this.inputText = '';
    this.scrollToBottom();
    
    try {
      await post('/consult/messages/send', {
        orderId: this.orderId,
        expertId: this.expertId,
        type: 'text',
        content: message.content
      });
      
      message.status = 'sent';
    } catch (error) {
      console.error('发送消息失败:', error);
      message.status = 'failed';
      
      uni.showToast({
        title: '发送失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 输入变化处理
   */
  onInputChange() {
    // 发送正在输入状态
    this.sendTypingStatus();
  }
  
  /**
   * 发送正在输入状态
   */
  async sendTypingStatus() {
    try {
      await post('/consult/typing', {
        orderId: this.orderId,
        expertId: this.expertId
      });
    } catch (error) {
      console.error('发送输入状态失败:', error);
    }
  }
  
  /**
   * 显示更多选项
   */
  showMoreOptions() {
    this.showOptionsPopup = true;
  }
  
  /**
   * 选择图片
   */
  selectImage() {
    this.showOptionsPopup = false;
    
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: (res) => {
        this.sendImageMessage(res.tempFilePaths[0]);
      }
    });
  }
  
  /**
   * 拍照
   */
  takePhoto() {
    this.showOptionsPopup = false;
    
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        this.sendImageMessage(res.tempFilePaths[0]);
      }
    });
  }
  
  /**
   * 发送图片消息
   */
  async sendImageMessage(imagePath: string) {
    if (!this.canSendMessage) return;
    
    const message: Message = {
      id: Date.now().toString(),
      type: 'image',
      content: imagePath,
      fromUser: true,
      createTime: new Date().toISOString(),
      status: 'sending'
    };
    
    this.messageList.push(message);
    this.scrollToBottom();
    
    try {
      // 上传图片
      const uploadResponse = await this.uploadImage(imagePath);
      message.content = uploadResponse.url;
      
      // 发送消息
      await post('/consult/messages/send', {
        orderId: this.orderId,
        expertId: this.expertId,
        type: 'image',
        content: message.content
      });
      
      message.status = 'sent';
    } catch (error) {
      console.error('发送图片失败:', error);
      message.status = 'failed';
      
      uni.showToast({
        title: '发送失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 上传图片
   */
  async uploadImage(imagePath: string): Promise<{ url: string }> {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: '/api/upload/image',
        filePath: imagePath,
        name: 'file',
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (error) {
            reject(error);
          }
        },
        fail: reject
      });
    });
  }
  
  /**
   * 开始语音录制
   */
  startVoiceRecord() {
    if (!this.canSendMessage) return;
    this.showVoiceRecord = true;
  }
  
  /**
   * 开始录制
   */
  startRecord() {
    this.isRecording = true;
    this.recordTime = 0;
    
    // 开始录音
    uni.startRecord({
      success: () => {
        this.recordTimer = setInterval(() => {
          this.recordTime++;
        }, 1000);
      },
      fail: (error) => {
        console.error('开始录音失败:', error);
        this.isRecording = false;
      }
    });
  }
  
  /**
   * 停止录制
   */
  stopRecord() {
    if (!this.isRecording) return;
    
    this.isRecording = false;
    clearInterval(this.recordTimer);
    
    uni.stopRecord({
      success: (res) => {
        this.sendVoiceMessage((res as any).tempFilePath, this.recordTime);
        this.showVoiceRecord = false;
      },
      fail: (error) => {
        console.error('停止录音失败:', error);
      }
    });
  }
  
  /**
   * 取消录制
   */
  cancelRecord() {
    this.isRecording = false;
    clearInterval(this.recordTimer);
    this.showVoiceRecord = false;
  }
  
  /**
   * 发送语音消息
   */
  async sendVoiceMessage(voicePath: string, duration: number) {
    if (!this.canSendMessage) return;
    
    const message: Message = {
      id: Date.now().toString(),
      type: 'voice',
      content: voicePath,
      fromUser: true,
      createTime: new Date().toISOString(),
      status: 'sending',
      duration
    };
    
    this.messageList.push(message);
    this.scrollToBottom();
    
    try {
      // 上传语音
      const uploadResponse = await this.uploadVoice(voicePath);
      message.content = uploadResponse.url;
      
      // 发送消息
      await post('/consult/messages/send', {
        orderId: this.orderId,
        expertId: this.expertId,
        type: 'voice',
        content: message.content,
        duration
      });
      
      message.status = 'sent';
    } catch (error) {
      console.error('发送语音失败:', error);
      message.status = 'failed';
      
      uni.showToast({
        title: '发送失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 上传语音
   */
  async uploadVoice(voicePath: string): Promise<{ url: string }> {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: '/api/upload/voice',
        filePath: voicePath,
        name: 'file',
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (error) {
            reject(error);
          }
        },
        fail: reject
      });
    });
  }
  
  /**
   * 播放语音
   */
  playVoice(message: Message) {
    if (message.playing) {
      uni.stopVoice();
      message.playing = false;
    } else {
      // 停止其他语音
      this.messageList.forEach(msg => {
        if (msg.type === 'voice') {
          msg.playing = false;
        }
      });
      
      message.playing = true;
      
      uni.playVoice({
        filePath: message.content,
        success: () => {
          message.playing = false;
        },
        fail: () => {
          message.playing = false;
        }
      });
    }
  }
  
  /**
   * 开始语音通话
   */
  startVoiceCall() {
    uni.showModal({
      title: '语音通话',
      content: '是否开始语音通话？',
      success: (res) => {
        if (res.confirm) {
          // 实现语音通话逻辑
          uni.showToast({
            title: '正在连接...',
            icon: 'loading'
          });
        }
      }
    });
  }
  
  /**
   * 开始视频通话
   */
  startVideoCall() {
    uni.showModal({
      title: '视频通话',
      content: '是否开始视频通话？',
      success: (res) => {
        if (res.confirm) {
          // 实现视频通话逻辑
          uni.showToast({
            title: '正在连接...',
            icon: 'loading'
          });
        }
      }
    });
  }
  
  /**
   * 预览图片
   */
  previewImage(imageUrl: string) {
    uni.previewImage({
      urls: [imageUrl],
      current: imageUrl
    });
  }
  
  /**
   * 显示咨询历史
   */
  showConsultHistory() {
    this.showOptionsPopup = false;
    uni.navigateTo({
      url: `/pages/consult/history?expertId=${this.expertId}`
    });
  }
  
  /**
   * 评价专家
   */
  evaluateExpert() {
    this.showOptionsPopup = false;
    uni.navigateTo({
      url: `/pages/evaluate/evaluate?orderId=${this.orderId}&expertId=${this.expertId}`
    });
  }
  
  /**
   * 加载更多消息
   */
  loadMoreMessages() {
    this.loadMessages(true);
  }
  
  /**
   * 滚动到底部
   */
  scrollToBottom() {
    this.$nextTick(() => {
      this.scrollTop = 999999;
    });
  }
  
  /**
   * 是否显示时间
   */
  shouldShowTime(index: number): boolean {
    if (index === 0) return true;
    
    const currentTime = new Date(this.messageList[index].createTime).getTime();
    const prevTime = new Date(this.messageList[index - 1].createTime).getTime();
    
    return currentTime - prevTime > 5 * 60 * 1000; // 5分钟
  }
  
  /**
   * 格式化时间
   */
  formatTime(seconds: number): string {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  }
  
  /**
   * 格式化录制时间
   */
  formatRecordTime(seconds: number): string {
    return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
  }
  
  /**
   * 格式化消息时间
   */
  formatMessageTime(timeString: string): string {
    const date = new Date(timeString);
    const now = new Date();
    
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else {
      return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    }
  }
  
  /**
   * 获取模拟订单数据
   */
  getMockOrder(): ConsultOrder {
    return {
      id: this.orderId,
      expertId: this.expertId,
      serviceType: this.serviceType,
      status: 'active',
      startTime: new Date().toISOString(),
      duration: 30 // 30分钟
    };
  }
  
  /**
   * 获取模拟专家数据
   */
  getMockExpert(): Expert {
    return {
      id: this.expertId,
      name: '张医生',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor&image_size=square',
      isOnline: true
    };
  }
  
  /**
   * 获取模拟消息数据
   */
  getMockMessages(): Message[] {
    return [
      {
        id: '1',
        type: 'system',
        content: '咨询已开始，请描述您的问题',
        fromUser: false,
        createTime: new Date(Date.now() - 10 * 60 * 1000).toISOString()
      },
      {
        id: '2',
        type: 'text',
        content: '您好，我想咨询一下宝宝的喂养问题',
        fromUser: true,
        createTime: new Date(Date.now() - 8 * 60 * 1000).toISOString(),
        status: 'read'
      },
      {
        id: '3',
        type: 'text',
        content: '您好，请详细描述一下宝宝的具体情况，比如年龄、体重等',
        fromUser: false,
        createTime: new Date(Date.now() - 7 * 60 * 1000).toISOString()
      }
    ];
  }
}
</script>

<style lang="scss" scoped>
.consult-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.expert-header {
  background-color: white;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .expert-info {
    display: flex;
    align-items: center;
    
    .expert-details {
      margin-left: 15rpx;
      
      .expert-name {
        display: block;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 5rpx;
      }
      
      .expert-status {
        .online-indicator {
          display: flex;
          align-items: center;
          
          .online-dot {
            width: 8rpx;
            height: 8rpx;
            background-color: #4caf50;
            border-radius: 50%;
            margin-right: 8rpx;
          }
          
          .status-text {
            font-size: 22rpx;
            color: #4caf50;
          }
        }
        
        .offline-indicator {
          .status-text {
            font-size: 22rpx;
            color: #999;
          }
        }
      }
    }
  }
  
  .consult-info {
    text-align: right;
    
    .service-type {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 5rpx;
    }
    
    .remaining-time {
      font-size: 22rpx;
      color: #ff4757;
    }
  }
}

.message-list {
  flex: 1;
  padding: 20rpx;
  
  .loading-more {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    
    .loading-text {
      margin-left: 10rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .message-item {
    margin-bottom: 30rpx;
    
    .time-divider {
      text-align: center;
      margin-bottom: 20rpx;
      
      .time-text {
        font-size: 22rpx;
        color: #999;
        background-color: rgba(0, 0, 0, 0.1);
        padding: 8rpx 16rpx;
        border-radius: 12rpx;
      }
    }
    
    .message-content {
      display: flex;
      align-items: flex-end;
      
      .message-avatar {
        margin: 0 15rpx;
      }
      
      .message-bubble {
        max-width: 500rpx;
        padding: 20rpx;
        border-radius: 20rpx;
        background-color: white;
        position: relative;
        
        &.bubble-self {
          background-color: #007aff;
          
          .message-text {
            color: white;
          }
        }
        
        .message-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          word-wrap: break-word;
        }
        
        .message-image {
          width: 200rpx;
          height: 200rpx;
          border-radius: 12rpx;
        }
        
        .voice-message {
          display: flex;
          align-items: center;
          min-width: 120rpx;
          
          .voice-duration {
            margin-left: 10rpx;
            font-size: 24rpx;
            color: white;
          }
        }
        
        .system-message {
          font-size: 24rpx;
          color: #666;
          text-align: center;
        }
      }
    }
    
    &.message-self {
      .message-content {
        flex-direction: row-reverse;
      }
    }
    
    .message-status {
      text-align: right;
      margin-top: 8rpx;
      
      .status-text {
        font-size: 20rpx;
        color: #999;
        
        &.error {
          color: #ff4757;
        }
      }
    }
  }
  
  .typing-indicator {
    display: flex;
    align-items: flex-end;
    margin-bottom: 30rpx;
    
    .message-avatar {
      margin-right: 15rpx;
    }
    
    .typing-bubble {
      background-color: white;
      padding: 20rpx;
      border-radius: 20rpx;
      
      .typing-dots {
        display: flex;
        gap: 8rpx;
        
        .dot {
          width: 8rpx;
          height: 8rpx;
          background-color: #999;
          border-radius: 50%;
          animation: typing 1.4s infinite ease-in-out;
          
          &:nth-child(1) {
            animation-delay: -0.32s;
          }
          
          &:nth-child(2) {
            animation-delay: -0.16s;
          }
        }
      }
    }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.input-area {
  background-color: white;
  padding: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .call-buttons {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
    
    .call-btn {
      flex: 1;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 30rpx;
      
      &.voice-btn {
        background-color: #4caf50;
      }
      
      &.video-btn {
        background-color: #2196f3;
      }
      
      .btn-text {
        margin-left: 8rpx;
        font-size: 24rpx;
        color: white;
      }
    }
  }
  
  .message-input-area {
    display: flex;
    align-items: center;
    gap: 15rpx;
    
    .input-tools {
      flex-shrink: 0;
    }
    
    .message-input {
      flex: 1;
      height: 70rpx;
      padding: 0 20rpx;
      background-color: #f8f8f8;
      border-radius: 35rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .send-area {
      flex-shrink: 0;
      
      .send-btn {
        width: 120rpx;
        height: 60rpx;
        font-size: 26rpx;
      }
    }
  }
}

.options-popup {
  background-color: white;
  border-radius: 20rpx 20rpx 0 0;
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .option-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 30rpx;
    padding: 40rpx 30rpx;
    
    .option-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .option-icon {
        width: 80rpx;
        height: 80rpx;
        background-color: #f0f8ff;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 15rpx;
      }
      
      .option-text {
        font-size: 24rpx;
        color: #333;
      }
    }
  }
}

.voice-record-popup {
  background-color: white;
  border-radius: 20rpx;
  padding: 40rpx;
  text-align: center;
  
  .record-header {
    margin-bottom: 40rpx;
    
    .record-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .record-content {
    margin-bottom: 40rpx;
    
    .record-animation {
      margin-bottom: 30rpx;
      
      .record-circle {
        width: 120rpx;
        height: 120rpx;
        background-color: #007aff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        transition: all 0.3s;
        
        &.recording {
          background-color: #ff4757;
          transform: scale(1.1);
          animation: pulse 1s infinite;
        }
      }
    }
    
    .record-time {
      display: block;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 15rpx;
    }
    
    .record-tip {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .record-actions {
    display: flex;
    gap: 20rpx;
    
    .record-btn {
      flex: 1;
      height: 80rpx;
      background-color: #007aff;
      color: white;
      border-radius: 40rpx;
      
      &.recording {
        background-color: #ff4757;
      }
    }
    
    .cancel-btn {
      flex: 0 0 120rpx;
      height: 80rpx;
      background-color: #f8f8f8;
      color: #666;
      border-radius: 40rpx;
    }
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 71, 87, 0.7);
  }
  70% {
    box-shadow: 0 0 0 20rpx rgba(255, 71, 87, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 71, 87, 0);
  }
}
</style>